package com.shove.web.action;

import com.alibaba.fastjson.JSONObject;
import com.allinpay.XmlTools;
import com.allinpay.aipg.common.AipgReq;
import com.allinpay.aipg.common.AipgRsp;
import com.allinpay.aipg.common.InfoReq;
import com.allinpay.aipg.common.XSUtil;
import com.allinpay.aipg.quickpay.FAGRA;
import com.allinpay.aipg.quickpay.FAGRC;
import com.allinpay.aipg.quickpay.FASTTRX;
import com.allinpay.aipg.transquery.QTDetail;
import com.allinpay.aipg.transquery.QTransRsp;
import com.allinpay.aipg.transquery.TransQueryReq;
import com.shove.Convert;
import com.shove.config.AllinpayConfig;
import com.shove.web.util.JSONUtils;
import com.sp2p.action.front.BaseFrontAction;
import com.sp2p.constants.IConstants;
import com.sp2p.entity.User;
import com.sp2p.service.HomeInfoSettingService;
import com.sp2p.service.RechargeService;
import com.sp2p.service.UserService;
import com.sp2p.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.sp2p.system.interceptor.FrontUserSeesionInterceptor.StringFilter;

public class AllinPaymentAction extends BaseFrontAction {
	private static final long serialVersionUID = 1L;
	private static Log log = LogFactory.getLog(AllinPaymentAction.class);

	String pfxPath = this.getClass().getResource("/").getPath().replace("classes", "config")+"//"+AllinpayConfig.alllin_p12;	//通联私钥路径
	String tltcerPath = this.getClass().getResource("/").getPath().replace("classes", "config")+"//"+AllinpayConfig.alllin_cer;	//通联公钥路径
	private String QAV_REQ_SN = ""; //对应签约申请请求报文中的REQ_SN
	private String urlParam = "";// 接口拼接的参数
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	private String tranAmt = ""; 	//充值金额
	private String orderId = "";	//订单编号
	Pattern p = Pattern.compile("[a-zA-z]");	//是否包含字母


	public String getUrlParam() {
		return urlParam;
	}

	public void setUrlParam(String urlParam) {
		this.urlParam = urlParam;
	}

	private RechargeService rechargeService;
	private UserService userService;
	private HomeInfoSettingService homeInfoSettingService;

	public HomeInfoSettingService getHomeInfoSettingService() {
		return homeInfoSettingService;
	}

	public void setHomeInfoSettingService(
			HomeInfoSettingService homeInfoSettingService) {
		this.homeInfoSettingService = homeInfoSettingService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public RechargeService getRechargeService() {
		return rechargeService;
	}

	public void setRechargeService(RechargeService rechargeService) {
		this.rechargeService = rechargeService;
	}

	SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
	boolean isfront=false;//是否发送至前置机（由前置机进行签名）如不特别说明，商户技术不要设置为true
	private String trx_code = "";//100001批量代收 100002批量代付 100011单笔实时代收 100014单笔实时代付

	/**
	 * 测试的时候不用修改以下业务代码，但上生产环境的时候，必须使用业务人员提供的业务代码，否则返回“未开通业务类型”
	 * 另外，特别说明：如果生产环境对接的时候返回”未开通产品“那么说明该商户开通的接口与目前测试的接口不一样，需要找业务确认
	 * 代收是批量代收接口的简称，代付 是批量代付接口的简称，
	 * 对接报文中，info下面的用户名一般是：商户号+04，比如商户号为：200604000000445，那么对接用户一般为：20060400000044504
	 */


	//是否绑定通联协议支付
	public String allinPayIsBindBankCard() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user == null) {
			return "noLogin";
		}

		String money = request("tranAmt");
		if (StringUtils.isBlank(money)) {
			return INPUT;
		}

		BigDecimal moneyDecimal;
		try {
			moneyDecimal = new BigDecimal(money);
		} catch (RuntimeException e) {
			return INPUT;
		}
		// 最小金额为0.01元
		int temp = moneyDecimal.compareTo(new BigDecimal("0.01"));
		if (temp < 0) {
			return INPUT;
		}
		request().setAttribute("tranAmt", money);

		List<Map<String, Object>> lists = homeInfoSettingService
				.querySuccessBankInfoList(user.getId());
		for (Map<String, Object> o : lists) {
			String isAllinpayCard = o.get("isAllinpayCard").toString();
			if (isAllinpayCard.equals("1")) {		//是否绑定通联协议支付（0：否 1：是）
				request().setAttribute("allinPayBankCard", o);
				request().setAttribute("tranAmt", money);
				return "allinPaySubmit";
			}
		}

		// 实名信息
		Map<String, String> personMap = userService.queryPersonById(user
				.getId());
		String realName = Convert.strToStr(personMap.get("realName"), "");
		String idNo = Convert.strToStr(personMap.get("idNo"), "");
		String cellPhone = Convert.strToStr(personMap.get("cellPhone"), "");
		if("".equals(realName)){
			return "allinPayBindBankCardAndIdNo";
		}else{
			request().setAttribute("realName", realName);
			request().setAttribute("idNo", idNo);
			request().setAttribute("cellPhone", cellPhone.substring(0, 3) + "****"+cellPhone.substring(8, 11));
		}
		return "allinPayBindBankCard";
	}

	//协议支付签约短信触发
	public void getAllinPayVerCode() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		//设置安全提供者,注意，这一步尤为重要
		BouncyCastleProvider provider = new BouncyCastleProvider();
		XmlTools.initProvider(provider);

		JSONObject resObj = new JSONObject();
		if (user == null) {
			resObj.put("msg", "noLogin");
			JSONUtils.printStr(resObj.toString());
			return;
		}

		// 实名信息
		Map<String, String> personMap = userService.queryPersonById(user
				.getId());
		String realName = StringFilter(Convert.strToStr(personMap.get("realName"), ""));
		String idNo = Convert.strToStr(personMap.get("idNo"), "");
		String cellPhone = Convert.strToStr(personMap.get("cellPhone"), "");
		String bankName = StringFilter(Convert.strToStr(paramMap.get("bankName"), null));
		String bankCode = StringFilter(Convert.strToStr(paramMap.get("bankCode"), null));
		String bankCard = StringFilter(Convert.strToStr(paramMap.get("bankCard"), null));
		String VAILDDATE = Convert.strToStr(paramMap.get("VAILDDATE"), null);

		if(p.matcher(realName).find() || isSpecialChar(realName))	//判断姓名是否包含字母或特殊字符
		{
			resObj.put("errCode", "failed");
			resObj.put("msg", "实名信息有误！");
			JSONUtils.printStr(resObj.toString());
			return;
		}
		if(p.matcher(bankName).find() || isSpecialChar(bankName))	//判断银行卡名称是否包含字母或特殊字符
		{
			resObj.put("errCode", "failed");
			resObj.put("msg", "银行卡信息有误！");
			JSONUtils.printStr(resObj.toString());
			return;
		}
		if(p.matcher(bankCard).find() || isSpecialChar(bankCard))	//判断银行卡号是否包含字母或特殊字符
		{
			resObj.put("errCode", "failed");
			resObj.put("msg", "银行卡号信息有误！");
			JSONUtils.printStr(resObj.toString());
			return;
		}

		String xml="";
		AipgReq aipgReq=new AipgReq();
		InfoReq info=makeReq("310001");
		aipgReq.setINFO(info);

		FAGRA valid=new FAGRA();
		valid.setACCOUNT_NAME(realName);		//借记卡或信用卡上的所有人姓名
		valid.setACCOUNT_NO(bankCard);		//借记卡或信用卡帐号
		valid.setVALIDDATE(VAILDDATE);
		valid.setBANK_CODE(bankCode);		//银行代码
		valid.setID(idNo);		//证件号
		valid.setID_TYPE("0");		//开户证件类型，0身份证
		valid.setMERCHANT_ID(AllinpayConfig.alllin_merchantId);		//商户号 ID
		valid.setTEL(cellPhone);		//手机号
		valid.setACCOUNT_TYPE("02");		//账号类型，00借记卡，02信用卡。不填默认为借记卡00
		valid.setACCOUNT_PROP("0");			//账号属性，0私人，1公司。不填时，默认为私人0
		valid.setREMARK("单笔实时身份验证获取短信");
		aipgReq.addTrx(valid);

		xml=XmlTools.buildXml(aipgReq,true);//
		String resp = sendToTlt(xml,isfront,AllinpayConfig.alllin_gate_way);
		dealRet(resp);

		session().setAttribute("bankName",bankName);
		session().setAttribute("bankCode",bankCode);
		session().setAttribute("bankCard",bankCard);

	}

	//协议支付签约短信确认页面
	public String allinPaySmsCode() throws Exception{
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user == null) {
			return "noLogin";
		}
		String SRCREQ_SN = Convert.strToStr(request().getParameter("SRCREQ_SN"), null);
		System.out.println("================"+SRCREQ_SN);
		request().setAttribute("mobile",user.getMobilePhone().substring(0, 3) + "****"+user.getMobilePhone().substring(8, 11));
		request().setAttribute("SRCREQ_SN",SRCREQ_SN);

		return SUCCESS;
	}


	//协议支付签约确认
	public void allinPaySmsCodeCheck() throws Exception{
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		//设置安全提供者,注意，这一步尤为重要
		BouncyCastleProvider provider = new BouncyCastleProvider();
		XmlTools.initProvider(provider);

		JSONObject resObj = new JSONObject();

		if (user == null) {
			resObj.put("msg", "noLogin");
			JSONUtils.printStr(resObj.toString());
			return;
		}

		String SRCREQ_SN = Convert.strToStr(paramMap.get("SRCREQ_SN"), null);
		String verCode = Convert.strToStr(paramMap.get("verCode"), null);
		String xml="";
		AipgReq aipgReq=new AipgReq();
		InfoReq info=makeReq("310002");
		aipgReq.setINFO(info);

		FAGRC valid=new FAGRC();
		valid.setMERCHANT_ID(AllinpayConfig.alllin_merchantId);
		valid.setSRCREQSN(SRCREQ_SN);
		valid.setVERCODE(verCode);
		aipgReq.addTrx(valid);

		xml=XmlTools.buildXml(aipgReq,true);//
		String resp = sendToTlt(xml,isfront,AllinpayConfig.alllin_gate_way);
		dealRet(resp);
	}

	//绑定协议支付成功页面
	public String bindAllinPaySuccess() throws Exception{
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user == null) {
			return "noLogin";
		}
		return SUCCESS;
	}

	//协议支付
	public String allinPayment() throws Exception {
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		//设置安全提供者,注意，这一步尤为重要
		BouncyCastleProvider provider = new BouncyCastleProvider();
		XmlTools.initProvider(provider);

		if (user == null) {
			return "noLogin";
		}

		tranAmt = Convert.strToStr(paramMap.get("tranAmt"), null);;
		String AGRMNO = "";		//签约成功返回的协议号

		if (StringUtils.isBlank(tranAmt)) {
			return INPUT;
		}

		BigDecimal moneyDecimal;
		try {
			moneyDecimal = new BigDecimal(tranAmt);
		} catch (RuntimeException e) {
			return INPUT;
		}
		//最小金额为0.01元
		int temp = moneyDecimal.compareTo(new BigDecimal("0.01"));
		if (temp < 0) {
			return INPUT;
		}

		int rechargeMoney = Convert.strToInt(tranAmt, 0)*100;		//通联充值金额，整数，单位分

		List<Map<String, Object>> lists = homeInfoSettingService
				.querySuccessBankInfoList(user.getId());
		for (Map<String, Object> o : lists) {
			String isAllinpayCard = o.get("isAllinpayCard").toString();
			if (isAllinpayCard.equals("1")) {		//是否绑定通联协议支付（0：否 1：是）
				AGRMNO = o.get("AGRMNO").toString();	//获取签约时返回的协议号
			}
		}
		// 实名信息

		Map<String, String> personMap = userService.queryPersonById(user
				.getId());
		String realName = Convert.strToStr(personMap.get("realName"), "");

			String xml="";
			AipgReq aipgReq=new AipgReq();
			InfoReq info=makeReq("310011");	//交易代码
			aipgReq.setINFO(info);

			FASTTRX valid=new FASTTRX();
			valid.setBUSINESS_CODE(AllinpayConfig.alllin_businessCode);	//业务代码
			valid.setMERCHANT_ID(AllinpayConfig.alllin_merchantId);		//商户代码
			valid.setACCOUNT_NAME(realName);		//借记卡或信用卡的所有人姓名
			/*valid.setACCOUNT_NO(bankCard);	//借记卡或信用卡帐号
			valid.setID(idNo);		//证件号
			valid.setID_TYPE("0");		//证件类型
			valid.setTEL(cellPhone);		//手机号
			valid.setCURRENCY("CNY");		//货币类型*/
			valid.setAMOUNT(String.valueOf(rechargeMoney));		//金额，整数，单位分
			valid.setAGRMNO(AGRMNO);	//签约时返回的协议号
			valid.setSUBMIT_TIME(new Date().toString());	//提交时间
			valid.setREMARK("单笔实时充值交易");
			aipgReq.addTrx(valid);

			xml=XmlTools.buildXml(aipgReq,true);//
			String resp = sendToTlt(xml,isfront,AllinpayConfig.alllin_gate_way);
			dealRet(resp);

		return null;
	}

	//充值成功页面
	public String rechargeSuccess() throws Exception{
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user == null) {
			return "noLogin";
		}
		return SUCCESS;
	}
	//充值失败页面
	public String rechargeFailed() throws Exception{
		User user = (User) session().getAttribute(IConstants.SESSION_USER);
		if (user == null) {
			return "noLogin";
		}
		return "failed";
	}


	/**
	 * @param reqsn 交易流水号
	 * @param url 通联地址
	 * @param isTLTFront 是否通过前置机
	 * @param startDate YYYYMMDDHHmmss
	 * @param endDate YYYYMMDDHHmmss
	 * 日期：Sep 4, 2012
	 * 功能：交易结果查询
	 * @throws Exception
	 */
	public void queryTradeNew(String url,String reqsn,boolean isTLTFront,String startDate,String endDate) throws Exception {
			String xml="";
			AipgReq aipgReq=new AipgReq();
			InfoReq info=makeReq("200004");
			aipgReq.setINFO(info);
			TransQueryReq dr=new TransQueryReq();
			aipgReq.addTrx(dr);
			dr.setMERCHANT_ID(AllinpayConfig.alllin_merchantId) ;
			dr.setQUERY_SN(reqsn);
			dr.setSTATUS(1);
			dr.setTYPE(1) ;
//		dr.setSTATUS(2);
			if(reqsn==null||"".equals(reqsn)){
				dr.setSTART_DAY(startDate);
				dr.setEND_DAY(endDate);
			}
			xml=XmlTools.buildXml(aipgReq,true);
			dealRet(sendToTlt(xml,isTLTFront,url));
	}


	/**
	 * 组装报文头部
	 * @param trxcod
	 * @return
	 *日期：Sep 9, 2012
	 */
	private InfoReq makeReq(String trxcod)
	{

		InfoReq info=new InfoReq();
		info.setTRX_CODE(trxcod);
		info.setREQ_SN(AllinpayConfig.alllin_merchantId+"-"+String.valueOf(System.currentTimeMillis()));
		/*info.setREQ_SN("200604000002185-151652861241991");*/
		info.setUSER_NAME(AllinpayConfig.alllin_userName);
		info.setUSER_PASS(AllinpayConfig.alllin_pfxPassword);
		info.setLEVEL(AllinpayConfig.alllin_level);
		info.setDATA_TYPE("2");
		info.setVERSION(AllinpayConfig.alllin_version);
		if("300000".equals(trxcod)||"300001".equals(trxcod)||"300003".equals(trxcod)||"REFUND".equals(trxcod)){
			info.setMERCHANT_ID(AllinpayConfig.alllin_merchantId);
		}
		return info;
	}

	public String sendXml(String xml,String url,boolean isFront) throws UnsupportedEncodingException, Exception{
		System.out.println("======================发送报文======================：\n"+xml);
		String resp=XmlTools.send(url,xml);
		System.out.println("======================响应内容======================") ;
		boolean flag= this.verifyMsg(resp, tltcerPath,isFront);
		if(flag){
			System.out.println("响应内容验证通过") ;
		}else{
			System.out.println("响应内容验证不通过") ;
		}
		return resp;
	}

	public String sendToTlt(String xml,boolean flag,String url) {
		try{
			if(!flag){
				xml=this.signMsg(xml);
			}else{
				xml=xml.replaceAll("<SIGNED_MSG></SIGNED_MSG>", "");
			}
			return sendXml(xml,url,flag);
		}catch(Exception e){
			e.printStackTrace();
			if(e.getCause() instanceof ConnectException ||e instanceof ConnectException){
				System.out.println("请求链接中断，如果是支付请求，请做交易结果查询，以确认该笔交易是否已被通联受理，避免重复交易");
			}
		}
		return "请求链接中断，如果是支付请求，请做交易结果查询，以确认该笔交易是否已被通联受理，避免重复交易";
	}
	/**
	 * 报文签名
	 * @param xml
	 * @return
	 *日期：Sep 9, 2012
	 * @throws Exception
	 */
	public String signMsg(String xml) throws Exception{

		xml=XmlTools.signMsg(xml, pfxPath,AllinpayConfig.alllin_pfxPassword, false);
		return xml;
	}

	/**
	 * 验证签名
	 * @param msg
	 * @return
	 *日期：Sep 9, 2012
	 * @throws Exception
	 */
	public boolean verifyMsg(String msg,String cer,boolean isFront) throws Exception{
		boolean flag=XmlTools.verifySign(msg, cer, false,isFront);
		System.out.println("验签结果["+flag+"]") ;
		return flag;
	}

	/**
	 * 返回报文处理逻辑
	 * @param retXml
	 */
	public void dealRet(String retXml) throws Exception {

		String trxcode = null;
		AipgRsp aipgrsp= null;
		//或者交易码
		if (retXml.indexOf("<TRX_CODE>") != -1)
		{
			int end = retXml.indexOf("</TRX_CODE>");
			int begin = end - 6;
			if (begin >= 0) trxcode = retXml.substring(begin, end);
		}
		aipgrsp= XSUtil.parseRsp(retXml);

		log.info("============报文处理xml============"+retXml);

		//协议支付签约短信触发
		if("310001".equals(trxcode)){
			JSONObject resObj = new JSONObject();
			if("0000".equals(aipgrsp.getINFO().getRET_CODE())) {	//请求成功

				if ("0000".equals(aipgrsp.getFAGRARET().getRET_CODE())) {	//触发成功
					resObj.put("errCode", "success");
					resObj.put("msg", "成功");
					resObj.put("SRCREQ_SN", aipgrsp.getINFO().getREQ_SN());
					JSONUtils.printStr(resObj.toString());
				} else {	//触发失败
					System.out.println("响应码" + aipgrsp.getFAGRARET().getRET_CODE() + "原因：" + aipgrsp.getFAGRARET().getERR_MSG());
					resObj.put("errCode", aipgrsp.getFAGRARET().getRET_CODE());
					resObj.put("msg", aipgrsp.getFAGRARET().getERR_MSG());
					JSONUtils.printStr(resObj.toString());
				}
			}else{		//请求失败
				System.out.println("响应码" + aipgrsp.getINFO().getRET_CODE() + "原因：" + aipgrsp.getINFO().getERR_MSG());
				resObj.put("errCode", aipgrsp.getINFO().getRET_CODE());
				resObj.put("msg", aipgrsp.getINFO().getERR_MSG());
				JSONUtils.printStr(resObj.toString());
			}
		}

		//协议支付签约确认
		if("310002".equals(trxcode)){
			User user = (User) session().getAttribute(IConstants.SESSION_USER);
			JSONObject resObj = new JSONObject();
			if("0000".equals(aipgrsp.getINFO().getRET_CODE())) {	//请求成功
				if ("0000".equals(aipgrsp.getFAGRCRET().getRET_CODE())) {	//绑卡成功
					String bankName = (String) session().getAttribute("bankName");
					String bankCode = (String) session().getAttribute("bankCode");
					String bankCard = (String) session().getAttribute("bankCard");
					String AGRMNO = aipgrsp.getFAGRCRET().getAGRMNO();        //签约成功返回签约协议号

					if(p.matcher(user.getRealName()).find() || isSpecialChar(user.getRealName()))	//判断姓名是否包含字母或特殊字符
					{
						resObj.put("errCode", "failed");
						resObj.put("msg", "实名信息有误！");
						JSONUtils.printStr(resObj.toString());
						return;
					}
					if(p.matcher(bankName).find() || isSpecialChar(bankName))	//判断银行卡名称是否包含字母或特殊字符
					{
						resObj.put("errCode", "failed");
						resObj.put("msg", "银行卡信息有误！");
						JSONUtils.printStr(resObj.toString());
						return;
					}
					if(p.matcher(bankCard).find() || isSpecialChar(bankCard))	//判断卡号是否包含字母或特殊字符
					{
						resObj.put("errCode", "failed");
						resObj.put("msg", "银行卡号信息有误！");
						JSONUtils.printStr(resObj.toString());
						return;
					}

					// 查询快捷卡绑定情况
					Map<String, String> allinpayBankCardMap = homeInfoSettingService
							.queryAllinpayBankCardInfo(user.getId());
					if (allinpayBankCardMap == null) {	//添加绑卡信息
						homeInfoSettingService.addAllinpayBankCardInfo(user.getId(), user
								.getRealName(), bankName, bankCode, bankName, bankCard, 1, AGRMNO);
					} else {	//修改绑卡信息
						long bankCardId = Convert.strToLong(allinpayBankCardMap.get("id"),
								-1);
						homeInfoSettingService.modifyAllinpayBankCardInfo(bankCardId,
								bankName, bankName, bankCode, bankCard, 1, AGRMNO);
					}
					session().removeAttribute("bankName");
					session().removeAttribute("bankCode");
					session().removeAttribute("bankCard");

					resObj.put("errCode", "success");
					resObj.put("msg", "成功");
					resObj.put("checkUrl", "/bindAllinPaySuccess.do");
					JSONUtils.printStr(resObj.toString());
				} else {	//绑卡失败
					System.out.println("响应码" + aipgrsp.getFAGRCRET().getRET_CODE() + "原因：" + aipgrsp.getFAGRCRET().getERR_MSG());
					resObj.put("errCode", aipgrsp.getFAGRCRET().getRET_CODE());
					resObj.put("msg", aipgrsp.getFAGRCRET().getERR_MSG());
					JSONUtils.printStr(resObj.toString());
				}
			}else{	//请求失败
				System.out.println("响应码" + aipgrsp.getINFO().getRET_CODE() + "原因：" + aipgrsp.getINFO().getERR_MSG());
				resObj.put("errCode", aipgrsp.getINFO().getRET_CODE());
				resObj.put("msg", aipgrsp.getINFO().getERR_MSG());
				JSONUtils.printStr(resObj.toString());
			}
		}

		//协议支付
		if("310011".equals(trxcode)){
			User user = (User) session().getAttribute(IConstants.SESSION_USER);
			String RECHARGE_REQ_SN = aipgrsp.getINFO().getREQ_SN();	//交易流水号
			JSONObject resObj = new JSONObject();

			BigDecimal moneyDecimal;
			try {
				moneyDecimal = new BigDecimal(tranAmt);
			} catch (RuntimeException e) {
				return ;
			}

			long userId = this.getUserId();
			paramMap.put("rechargeMoney", moneyDecimal + "");	//充值金额
			paramMap.put("userId", userId + "");		//用户ID
			paramMap.put("rechargeNumber", RECHARGE_REQ_SN);	//充值流水号
			paramMap.put("result", "0");		//处理结果，0未成功
			paramMap.put("addTime", DateUtil.dateToString(new Date()));		//提交时间

			//添加充值明细;24 ：通联协议支付
			Map<String, String> result = rechargeService.addRecharge(paramMap, 24);
			long nunber = Convert.strToInt(result.get("result"), -1);
			orderId = Convert.strToStr(String.valueOf(nunber),"");	//订单编号

			if (nunber != -1) {
				if ("0000".equals(aipgrsp.getINFO().getRET_CODE())) {	//请求成功

					// 平台账号充值
					if ("0000".equals(aipgrsp.getFASTTRXRET().getRET_CODE())) {		//充值成功

						String remarks = "通联支付充值成功，充值金额：￥" + tranAmt;
						Map<String, String> resultMap = rechargeService.addUseraddmoney(userId, Convert.strToDouble(tranAmt, 0), orderId, remarks);
						String res = resultMap.get("result");
						log.info("===================>>>平台账号充值，result：" + res);

						resObj.put("errCode", "success");
						resObj.put("msg", "成功");
						resObj.put("successUrl", "/rechargeSuccess.do");
						JSONUtils.printStr(resObj.toString());

					} else {	//充值失败
						System.out.println("响应码" + aipgrsp.getFASTTRXRET().getRET_CODE() + "原因：" + aipgrsp.getFASTTRXRET().getERR_MSG());
						resObj.put("errCode", aipgrsp.getFASTTRXRET().getRET_CODE());
						resObj.put("msg", aipgrsp.getFASTTRXRET().getERR_MSG());
						JSONUtils.printStr(resObj.toString());
					}

				} else {	//请求失败
					System.out.println("响应码" + aipgrsp.getINFO().getRET_CODE() + "原因：" + aipgrsp.getINFO().getERR_MSG());
					resObj.put("errCode", aipgrsp.getINFO().getRET_CODE());
					resObj.put("msg", aipgrsp.getINFO().getERR_MSG());
					JSONUtils.printStr(resObj.toString());
				}
			} else {	 // 支付失败
				resObj.put("errCode", "failed");
				resObj.put("msg", "充值失败，请稍后再试！");
				JSONUtils.printStr(resObj.toString());
			}
		}

		//交易查询处理逻辑
		if("200004".equals(trxcode)||"200005".equals(trxcode)){
			if("0000".equals(aipgrsp.getINFO().getRET_CODE())){		//请求成功

				QTransRsp qrsq=(QTransRsp) aipgrsp.getTrxData().get(0);
				System.out.println("查询成功，具体结果明细如下:");
				List<QTDetail> details=qrsq.getDetails();
				for(QTDetail lobj:details){
					System.out.print("原支付交易批次号:"+lobj.getBATCHID()+"  ");
					System.out.print("记录序号:"+lobj.getSN()+"  ");
					System.out.print("账号:"+lobj.getACCOUNT_NO()+"  ");
					System.out.print("户名:"+lobj.getACCOUNT_NAME()+"  ");
					System.out.print("金额:"+lobj.getAMOUNT()+"  ");
					System.out.print("返回结果:"+lobj.getRET_CODE()+"  ");

					if("0000".equals(lobj.getRET_CODE())){		//处理成功
						System.out.println("返回说明:交易成功  ");
						String remarks = "通联支付充值成功，充值金额：￥" + lobj.getAMOUNT();
						long result = rechargeService.updateRechargeDetailByRN(lobj.getBATCHID(), 1, remarks);
						log.info("===================>>>平台账号充值，result：" + result);

					}else{		//处理失败
						System.out.println("返回说明:"+lobj.getERR_MSG()+"  ");
					}
				}
			}else if("2000".equals(aipgrsp.getINFO().getRET_CODE())
					||"2001".equals(aipgrsp.getINFO().getRET_CODE())
					||"2003".equals(aipgrsp.getINFO().getRET_CODE())
					||"2005".equals(aipgrsp.getINFO().getRET_CODE())
					||"2007".equals(aipgrsp.getINFO().getRET_CODE())
					||"2008".equals(aipgrsp.getINFO().getRET_CODE())){
				System.out.print("返回说明:"+aipgrsp.getINFO().getRET_CODE()+"  ");
				System.out.println("返回说明："+aipgrsp.getINFO().getERR_MSG());
				System.out.println("该状态时，说明整个批次的交易都在处理中");
			}else if("2004".equals(aipgrsp.getINFO().getRET_CODE())){
				System.out.println("整批交易未受理通过（最终失败）");
			}else if("1002".equals(aipgrsp.getINFO().getRET_CODE())){
				System.out.println("查询无结果集（表示通联端根据商户请求上送的条件查不到对应的结果集）");
			}else{
				System.out.println("查询请求失败，请重新发起查询");
			}
		}
	}

	/**
	 * 判断是否含有特殊字符
	 *
	 * @param str
	 * @return true为包含，false为不包含
	 */
	public static boolean isSpecialChar(String str) {
		String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(str);
		return m.find();
	}

}

